package com.fcwy.puzzle;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fcwy.puzzle.adapter.GridItemsAdapter;
import com.fcwy.puzzle.domain.ItemBean;
import com.fcwy.puzzle.utils.AppConstant;
import com.fcwy.puzzle.utils.GameUtil;
import com.fcwy.puzzle.utils.HImage;
import com.fcwy.puzzle.utils.HLog;
import com.fcwy.puzzle.utils.HToast;
import com.fcwy.puzzle.utils.ImageLoaderUtil;
import com.fcwy.puzzle.utils.ImageUtil;
import com.fcwy.puzzle.utils.MD5;
import com.fcwy.puzzle.utils.PathUtil;
import com.fcwy.puzzle.utils.ScreenUtil;
import com.fcwy.puzzle.view.PopupWindowBrowse;
import com.fcwy.puzzle.view.PopupWindowBrowse.CheckboxClickListener;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;

/**
 * 拼图逻辑主界面：面板显示
 * 
 * @author lanyj
 * 
 */
public class MainActivity extends Activity implements OnClickListener ,OnTouchListener{

    // 选择的图片
    private Bitmap picSelected;
    // 拼图完成时显示的最后一个图片
    public static Bitmap lastBitmap;
    // PuzzlePanel
    private GridView gv_puzzle_main_detail;
    private int resId;
    private String picPath;
    private ImageView imageView;
    // Button
    private ImageButton btnBack;
    private ImageButton btn_refresh;
    private ImageButton btn_select;
    private ImageButton btn_local;
    private ImageButton btnRestart;
    // 显示步数
    private TextView tv_puzzle_main_counts;
    // 计时器
    private TextView tv_Timer;
    // 切图后的图片
    private List<Bitmap> bitmapItemLists = new ArrayList<Bitmap>();
    // GridView适配器
    private GridItemsAdapter adapter;
    // 设置为N*N显示
    public static int type = 3;
    // Flag 是否已显示原图
    private boolean isShowImg;
    // 步数显示
    public static int countIndex = 0;
    // 计时显示
    public static int timerIndex = 0;
    // 计时器类
    private Timer timer;
    private int[][] photoMap=null; 
    private long mLastBackPress;
	private static final long mBackPressThreshold = 3000;
	private static final int SELECT_PIC_BY_PICK_PHOTO = 1;
	private Toast pressBackToast;
    /**
     * UI更新Handler
     */
	private int autoIdx=0;
	private final int photoLength=56;
	private ImageView iv_photo;
	private PopupWindowBrowse browseWindow;
	private LinearLayout rootLayout;
	private String selectPath=null;
	private int selectPos=0;
    private Handler handler = new Handler() {

	@Override
	public void handleMessage(Message msg) {
	    switch (msg.what) {
	    case 1:
		// 更新计时器
		timerIndex++;
		tv_Timer.setText(GameUtil.timeParser(timerIndex));
		break;
	    default:
		break;
	    }
	}
    };

    /**
     * 计时器线程
     */
    private TimerTask timerTask;

    @SuppressLint("ShowToast")
	@Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	// 选择默认图片还是自定义图片
	resId = R.drawable.photo;
	// 对图片处理
	pressBackToast = Toast.makeText(getApplicationContext(),"再按一次退出游戏", Toast.LENGTH_SHORT);
	// 初始化Views
	initViews();
	// 获取选择的图片
	initPuzzlePhoto();
	// 生成游戏数据
	generateGame();
	// GridView点击事件
//	gv_puzzle_main_detail.setOnItemClickListener(new OnItemClickListener() {
//
//	    @Override
//	    public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
//	    	doItemSelect(position);
//	    }
//	});
	gv_puzzle_main_detail.setOnTouchListener(this);
	// 返回按钮点击事件
	btnBack.setOnClickListener(this);
	btn_refresh.setOnClickListener(this);
	// 显示原图按钮点击事件
	//btnImage.setOnClickListener(this);
	// 重置按钮点击事件
	btnRestart.setOnClickListener(this);
	btn_select.setOnClickListener(this);
	btn_local.setOnClickListener(this);
	iv_photo.setOnClickListener(this);
	//checkAppUpdate();
    }

    /**
     * Button点击事件
     */
    @Override
    public void onClick(View v) {
	switch (v.getId()) {
//	// 返回按钮点击事件
	case R.id.btn_back:
	    finish();
	    break;
//	// 显示原图按钮点击事件
//	case R.id.btn_puzzle_main_img:
//	    Animation animShow = AnimationUtils.loadAnimation(PuzzleMain.this, R.anim.image_show_anim);
//	    Animation animHide = AnimationUtils.loadAnimation(PuzzleMain.this, R.anim.image_hide_anim);
//	    if (isShowImg) {
//		imageView.startAnimation(animHide);
//		imageView.setVisibility(View.GONE);
//		isShowImg = false;
//	    } else {
//		imageView.startAnimation(animShow);
//		imageView.setVisibility(View.VISIBLE);
//		isShowImg = true;
//	    }
//	    break;
//	// 重置按钮点击事件
	case R.id.btn_start:
	case R.id.btn_refresh:
		initPuzzlePhoto();
	    cleanConfig();
	    generateGame();
	    recreateData();
	    // 通知GridView更改UI
	    tv_puzzle_main_counts.setText("" + countIndex);
	    adapter.notifyDataSetChanged();
	    gv_puzzle_main_detail.setEnabled(true);
	    break;
	case R.id.iv_photo:
		List<String> listUrl=new ArrayList<String>();
		listUrl.add(selectPath);
		browseWindow = new PopupWindowBrowse(MainActivity.this,listUrl,0,picSelected,null);
		browseWindow.showAtLocation(rootLayout,
				Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);			
		break;
	case R.id.btn_select:
		final List<String> listPhoto=new ArrayList<String>();
//		for(int i=2;i<=photoLength;i++) {
//			String url=AppConstant.BASE_PHOTO_URL+i+".jpg";
//			listPhoto.add(url);			
//		}
		CheckboxClickListener listner=new CheckboxClickListener() {
			
			@Override
			public void onConfirm(int position) {
				// TODO Auto-generated method stub	
				selectPos=position;
				selectPath=PathUtil.CACHE_IMG+MD5.md5(listPhoto.get(position));
        		Bitmap picSelectedTemp=HImage.getLocalThumbImg(selectPath, 720, 1280);
        		if(picSelectedTemp==null) {
        			picSelectedTemp=BitmapFactory.decodeResource(getResources(), resId);
        		}
        		iv_photo.setImageBitmap(picSelectedTemp);
        		handlerImage(picSelectedTemp);
				cleanConfig();
			    generateGame();
			    recreateData();
			    // 通知GridView更改UI
			    tv_puzzle_main_counts.setText("" + countIndex);
			    adapter.notifyDataSetChanged();
			    gv_puzzle_main_detail.setEnabled(true);
			}
		};
		browseWindow = new PopupWindowBrowse(MainActivity.this,listPhoto,selectPos,null,listner);
		browseWindow.showAtLocation(rootLayout,
				Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);	
		break;
	case R.id.btn_local:
		//本地相册
		pickPhoto();
		break;
	}
    }
    private void pickPhoto() {
		// TODO Auto-generated method stub
		Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(choosePictureIntent, SELECT_PIC_BY_PICK_PHOTO);
	}
	private void initPuzzlePhoto() {
//		int id=new Random().nextInt(photoLength-2)+2;
//		selectPos=id-2;
		//selectPath=PathUtil.CACHE_IMG+MD5.md5(AppConstant.BASE_PHOTO_URL+id+".jpg");
		Bitmap picSelectedTemp=null;//HImage.getLocalBitMap(MainActivity.this, selectPath, false);
		if(picSelectedTemp==null) {
			picSelectedTemp=BitmapFactory.decodeResource(getResources(), resId);
		}
		iv_photo.setImageBitmap(picSelectedTemp);
		handlerImage(picSelectedTemp);
		
	}

    /**
     * 生成游戏数据
     */
    private void generateGame() {
	// 切图 获取初始拼图数据 正常顺序
	new ImageUtil().createInitBitmaps(type, picSelected, MainActivity.this);
	// 生成随机数据
	GameUtil.getPuzzleGenerator();
	// 获取Bitmap集合
	//int length=GameUtil.itemBeans.size();
	photoMap=new int[type][type];
	for (ItemBean temp : GameUtil.itemBeans) {
	   bitmapItemLists.add(temp.getBitmap());	   
	}
	for(int y=0;y<type;y++) {
		for(int x=0;x<type;x++) {
			photoMap[x][y]=x+y*type;
		}
	}
	autoIdx = photoMap.length - 1;
	// 数据适配器
	adapter = new GridItemsAdapter(this, bitmapItemLists);
	gv_puzzle_main_detail.setAdapter(adapter);

	// 启用计时器
	timer = new Timer(true);
	// 计时器线程
	timerTask = new TimerTask() {

	    @Override
	    public void run() {
	    	handler.sendEmptyMessage(1);
	    }
	};
	// 每1000ms执行 延迟0s
	timer.schedule(timerTask, 0, 1000);
    }
    public void checkAppUpdate() {
		//检查更新
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
			
			@Override
			public void onUpdateReturned(int updateStatus,UpdateResponse updateInfo) {			
				switch (updateStatus) {
				case UpdateStatus.Yes: // has update
						UmengUpdateAgent.showUpdateDialog(MainActivity.this, updateInfo);
					break;
				case UpdateStatus.Timeout: // time out
						//HToast.showShortText(MainActivity.this, "网络连接超时");
					break;
				}
			}
			
		});
		UmengUpdateAgent.update(MainActivity.this);				
	}
    /**
     * 添加显示原图的View
     */
    private void addImgView() {
//	RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rl_puzzle_main_main_layout);
//	imageView = new ImageView(PuzzleMain.this);
//	imageView.setImageBitmap(picSelected);
//	int x = (int) (picSelected.getWidth() * 0.9F);
//	int y = (int) (picSelected.getHeight() * 0.9F);
//	LayoutParams params = new LayoutParams(x, y);
//	params.addRule(RelativeLayout.CENTER_IN_PARENT);
//	imageView.setLayoutParams(params);
//	relativeLayout.addView(imageView);
//	imageView.setVisibility(View.GONE);
    }

    /**
     * 返回时调用
     */
    @Override
    protected void onStop() {
	super.onStop();
	// 清空相关参数设置
	cleanConfig();
    }

    /**
     * 清空相关参数设置
     */
    private void cleanConfig() {
	// 清空相关参数设置
	GameUtil.itemBeans.clear();
	// 停止计时器
	timer.cancel();
	timerTask.cancel();
	countIndex = 0;
	timerIndex = 0;
	// 清除拍摄的照片
	if (picPath != null) {
	    // 删除照片
//	    File file = new File(MainActivity.TEMP_IMAGE_PATH);
//	    if (file.exists()) {
//		file.delete();
//	    }
	}
    }

    /**
     * 重新获取图片
     */
    private void recreateData() {
	bitmapItemLists.clear();
	for (ItemBean temp : GameUtil.itemBeans) {
	    bitmapItemLists.add(temp.getBitmap());
	}
    }

    /**
     * 对图片处理 自适应大小
     * 
     * @param bitmap
     */
    private void handlerImage(Bitmap bitmap) {
	// 将图片放大到固定尺寸
	int screenWidth = ScreenUtil.getScreenSize(this).widthPixels;
	int screenHeigt = ScreenUtil.getScreenSize(this).heightPixels;
	picSelected = new ImageUtil().resizeBitmap(screenWidth * 0.8f, screenHeigt * 0.6f, bitmap);
    }

    /**
     * 初始化Views
     */
    private void initViews() {
	// Button  	
	btnBack = (ImageButton) findViewById(R.id.btn_back);
	//btnImage = (ImageButton) findViewById(R.id.btn_puzzle_main_img);
	btn_refresh = (ImageButton) findViewById(R.id.btn_refresh);
	btnRestart = (ImageButton) findViewById(R.id.btn_start);
	btn_select = (ImageButton) findViewById(R.id.btn_select);
	btn_local = (ImageButton) findViewById(R.id.btn_local);
	// Flag 是否已显示原图
	isShowImg = false;
	rootLayout=(LinearLayout)findViewById(R.id.puzzle_main_main_layout);
	// GV
	gv_puzzle_main_detail = (GridView) findViewById(R.id.gv_puzzle_main_detail);
	// 设置为N*N显示
	gv_puzzle_main_detail.setNumColumns(type);

	// TV步数
	tv_puzzle_main_counts = (TextView) findViewById(R.id.tv_step);
	tv_puzzle_main_counts.setText("" + countIndex);
	// TV计时器
	tv_Timer = (TextView) findViewById(R.id.tv_time);
	tv_Timer.setText("0秒");
	iv_photo= (ImageView) findViewById(R.id.iv_photo);
//	ImageView iv_temp = (ImageView) findViewById(R.id.iv_temp);
//	for(int i=2;i<=photoLength;i++) {
//		String url=AppConstant.BASE_PHOTO_URL+i+".jpg";
//		Drawable defaultDraw= getResources().getDrawable(R.drawable.blank);
//		ImageLoaderUtil.loadImageAsync("MainActivity",iv_temp, url, PathUtil.CACHE_IMG, 
//        		defaultDraw, 600); 
//	}
	// 添加显示原图的View
	addImgView();
    }

    private float startX,startY,offsetX,offsetY,lastX,lastY;

	@Override
	public boolean onTouch(View v, MotionEvent event) {

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			startX = event.getX();
			startY = event.getY();
			lastX=(int)event.getRawX();
			lastY=(int)event.getRawY();
			break;
		case MotionEvent.ACTION_UP:
			offsetX = event.getX()-startX;
			offsetY = event.getY()-startY;
			// 若 up 与 down 都为同一个点则认为是点击事件
			if(Math.abs(event.getRawX() - lastX) <= 1 && Math.abs(event.getRawY() - lastY) <= 1){
				
			}
			if (Math.abs(offsetX)>Math.abs(offsetY)) {
				if (offsetX<-5) {
					//向左
					swipeLeft();
				}else if (offsetX>5) {
					//向右
					swipeRight();
				}
			}else{
				if (offsetY<-5) {
					//向上
					swipeUp();
				}else if (offsetY>5) {
					//向下
					swipeDown();
				}
			}
			
			break;
		}
		return true;
	}
	private void swipeLeft() {
		// 获取空格Item
		int blankId = GameUtil.blankItemBean.getItemId() - 1;
		boolean isMove=false;
		for(int y=0;y<photoMap.length;y++) {
			for(int x=0;x<photoMap.length;x++) {
				int position=photoMap[x][y];
				if(blankId==position) {
					for(int x1=x;x1<photoMap.length;x1++) {
						int selectPos=photoMap[x1][y];
						isMove=doItemSelect(selectPos);
						if(isMove)break;
					}					
				}
				if(isMove)break;
			}
			if(isMove)break;
		}		
	}
	private void swipeRight() {
		// 获取空格Item
		int blankId = GameUtil.blankItemBean.getItemId() - 1;
		boolean isMove=false;
		for(int y=0;y<photoMap.length;y++) {
			for(int x=0;x<photoMap.length;x++) {
				int position=photoMap[x][y];
				if(blankId==position) {
					for(int x1=x;x1>=0;x1--) {
						int selectPos=photoMap[x1][y];
						isMove=doItemSelect(selectPos);
						if(isMove)break;
					}					
				}
				if(isMove)break;
			}
			if(isMove)break;
		}
	}
	private void swipeUp() {
		// 获取空格Item
		int blankId = GameUtil.blankItemBean.getItemId() - 1;
		boolean isMove=false;
		for(int x=0;x<photoMap.length;x++) {
			for(int y=0;y<photoMap.length;y++) {
				int position=photoMap[x][y];
				if(blankId==position) {
					for(int y1=y;y1<photoMap.length;y1++) {
						int selectPos=photoMap[x][y1];
						isMove=doItemSelect(selectPos);
						if(isMove)break;
					}					
				}
				if(isMove)break;
			}
			if(isMove)break;
		}
		
	}
	private void swipeDown() {
		// 获取空格Item
		int blankId = GameUtil.blankItemBean.getItemId() - 1;
		boolean isMove=false;
		for(int x=0;x<photoMap.length;x++) {
			for(int y=0;y<photoMap.length;y++) {
				int position=photoMap[x][y];
				if(blankId==position) {
					for(int y1=y;y1>=0;y1--) {
						int selectPos=photoMap[x][y1];
						isMove=doItemSelect(selectPos);
						if(isMove)break;
					}					
				}
				if(isMove)break;
			}
			if(isMove)break;
		}
	}
	private boolean doItemSelect(int position) {
		boolean isMove=false;
		// 判断是否可移动
		if (GameUtil.isMoveable(position)) {
		    // 交换点击Item与空格的位置
		    GameUtil.swapItems(GameUtil.itemBeans.get(position), GameUtil.blankItemBean);
		    // 重新获取图片
		    recreateData();
		    // 通知GridView更改UI
		    adapter.notifyDataSetChanged();
		    // 更新步数
		    countIndex++;
			tv_puzzle_main_counts.setText("" + countIndex);
		    isMove=true;
		    // 判断是否成功
		    if (GameUtil.isSuccess()) {
		    	// 将最后一张图显示完整
		    	recreateData();
		    	bitmapItemLists.remove(type * type - 1);
		    	bitmapItemLists.add(lastBitmap);
		    	// 通知GridView更改UI
		    	adapter.notifyDataSetChanged();
		    	Toast.makeText(MainActivity.this, "恭喜，拼图成功！", Toast.LENGTH_LONG).show();
		    	gv_puzzle_main_detail.setEnabled(false);
		    	timer.cancel();
		    	timerTask.cancel();
		    }
		}
		return isMove;
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			 if(requestCode==SELECT_PIC_BY_PICK_PHOTO) {
				//选择图库图片结果
				Uri photoUri = data.getData();
				selectPath = HImage.getPicPathFromUri(photoUri, this);	
        		Bitmap picSelectedTemp=HImage.getLocalThumbImg(selectPath, 720, 1280);
        		if(picSelectedTemp==null) {
        			picSelectedTemp=BitmapFactory.decodeResource(getResources(), resId);
        		}
        		iv_photo.setImageBitmap(picSelectedTemp);
        		handlerImage(picSelectedTemp);
        		cleanConfig();
        	    generateGame();
        	    recreateData();
        	    // 通知GridView更改UI
        	    tv_puzzle_main_counts.setText("" + countIndex);
        	    adapter.notifyDataSetChanged();
        	    gv_puzzle_main_detail.setEnabled(true);
			}
		}
	}
	@Override 
	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);       //统计时长
	}
	@Override 
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(timer!=null) {
			timer.cancel();
			timerTask.cancel();
		}
	}
	@Override
	public void onBackPressed() {
	    long currentTime = System.currentTimeMillis();
	    if (Math.abs(currentTime - mLastBackPress) > mBackPressThreshold) {
	        pressBackToast.show();
	        mLastBackPress = currentTime;
	    } else {
	    	pressBackToast.cancel();
	        super.onBackPressed();
	    }
	}
}

